/**
 * 防抖
 * @param {Function} fn 用于防抖的函数
 * @param {Number} delay 延迟时间
 */
const debounce = (fn = () => {}, delay = 300) => {
  let time;
  return (...args) => {
    clearTimeout(time);
    time = setTimeout(() => fn(...args), delay);
  };
};

/**
 * 节流
 * @param {Function} fn 用于节流的函数
 * @param {Number} wait 等待时间（默认300毫秒）
 * @param {Boolean} immediately 是否立即执行第一次函数调用（默认是）
 */
const throttling = (fn = () => {}, wait = 300, immediately = true) => {
  let time;
  return (...args) => {
    if (!time) {
      time = setTimeout(() => {
        time = null;
        !immediately && fn(...args);
      }, wait);
      immediately && fn(...args);
    }
  };
};

/**
 * 获取元素
 * @param {String} selectors 包含一个或多个要匹配的选择器的DOM字符串DOMString
 */
const $ = (selectors) => document.querySelector(selectors);

/**
 * 解析URL参数
 * @param {*} url
 */
const parseUrl = (url = '') => {
  if (!url) throw Error('请输入URL地址');
  try {
    const [origin, search] = url.split('?');
    const params = {};
    search?.split('&')?.map((item) => {
      const [key, value] = item.split('=');
      if (key) params[key] = value || '';
    });
    return { origin, params };
  } catch (err) {
    throw Error('URL地址有误');
  }
};

// 模块化
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD
    define(['jquery', 'underscore'], factory);
  } else if (typeof exports === 'object') {
    // Node, CommonJS之类的
    module.exports = factory(require('jquery'), require('underscore'));
  } else {
    // 浏览器全局变量(root 即 window)
    root.returnExports = factory(root.jQuery, root._);
  }
})(this, function () {
  // 暴露公共方法
  return { debounce, throttling, $, parseUrl };
});
